package com.mazong.serversecbasic.security;

import com.mazong.serversecbasic.pojo.TbUser;
import com.mazong.serversecbasic.service.impl.MyUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    MyUserDetailsService myUserDetailsService;

    /**
     * 自定义验证用户名和密码
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //--1 表单输入的用户名和密码
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        log.info("username={},password={}", username, password);

        UserDetails user = myUserDetailsService.loadUserByUsername(username);
        if(null == user) {
            throw new BadCredentialsException("用户不存在!");
        }

        String encode = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!user.getPassword().equals(encode)) {
            throw new BadCredentialsException("密码不正确!");
        }

        log.info("role={}", user.getAuthorities().size());
        for(GrantedAuthority grantedAuthority : user.getAuthorities()) {
            log.info("roles={}", grantedAuthority.getAuthority());
        }

        return new UsernamePasswordAuthenticationToken(username, user.getPassword(), user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
